package com.dashan.servlets;

import static com.dashan.Constants.USERNAME;
import static com.dashan.servlets.Parameter.Option.Required;

import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;

import javax.jdo.JDOObjectNotFoundException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.dashan.backend.AuthenticationManager;
import com.dashan.backend.datastore.DsUser;
import com.dashan.backend.datastore.UserDao;
import com.dashan.backend.util.EncriptionHelper;
import com.dashan.backend.util.XmlHelper;

@SuppressWarnings("serial")
public class GetSaltServlet extends DashanServlet {

    @Override
    public ArrayList<Parameter> getParameterList() {
        ArrayList<Parameter> res = super.getParameterList();
        res.add(new Parameter(USERNAME, Required, String.class));
        return res;
    }

    @Override
    public String getUrlPattern() {
       return "/getsalt";
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        TreeMap<String, Parameter> params = loadParamters(req);
        
        UserDao dao = new UserDao();
        try {
            
                String salt = AuthenticationManager.getSalt(params.get(USERNAME).stringValue());
                Document xmlDoc = XmlHelper.createXmlDocument("response");
                Element root = xmlDoc.createElement("authentication");
                Element ele = xmlDoc.createElement("salt");
                ele.appendChild(xmlDoc.createTextNode(salt));
                root.appendChild(ele);
//                xmlDoc.getDocumentElement().appendChild(ele);
                DsUser user = dao.getUser(params.get(USERNAME).stringValue());
                String saltedPwdSha = EncriptionHelper.saltPwd(user.getPwdSha(), salt);
                // TODO(linfan): Remove this code after test.
                // For test only.
                ele = xmlDoc.createElement("saltedpwdsha");
                ele.appendChild(xmlDoc.createTextNode(saltedPwdSha));
                root.appendChild(ele);
                xmlDoc.getDocumentElement().appendChild(root);                
                /////////////////////////////////////////////
                resp.getWriter().print(XmlHelper.xml2String(xmlDoc));
        } catch (JDOObjectNotFoundException e) {
            throw new ServletException(e.getMessage());
        } finally {
            dao.commit();
        }            
    }

}
